<template>
  <div id="app">
    <router-view />
  </div>
</template>

<script>
import mqtt from 'mqtt'
import { MqttHelper, config, subList, evbusMap } from '@/utils/mqttHelper'
var showlog = false
var M = null
export default {
  name: 'App',
  created() {},
  mounted() {
    this.connect()
  },
  methods: {
    connect() {
      try {
        const { protocol, host, port, endpoint, ...options } = config
        const connectUrl = `${protocol}://${host}:${port}${endpoint}`
        showlog && console.log('Connection options!', options)
        this.client = mqtt.connect(connectUrl, options)
        M = new MqttHelper(this.client)
        this.client.on('connect', () => {
          showlog && console.log('mqtt 服务连接成功!')
          for (let sub of subList) M.doSubscribe(sub)
        })
        this.client.on('reconnect', () => {
          console.log('正在尝试重新连接！')
        })
        this.client.on('error', (error) => {
          showlog && console.log('mqtt 发生异常：', error)
        })
        this.client.on('message', (topic, message) => {
          this.updateAfterReceived(topic, message)
        })
      } catch (error) {
        showlog && console.log('mqtt 连接失败!', error)
      }
    },

    updateAfterReceived(topic, msg) {
      const newData = JSON.parse(msg.toString())
      showlog && console.log(`call App updateAfterReceived:`, newData)
      const packType = newData.PackType
      for (let t of evbusMap) {
        // console.log( topic, packType, t.packType)
        if (topic.indexOf(t.topicKeyWord) > -1 && packType == t.packType) {
          // console.log(t.topicKeyWord, packType)
          t.relayEvent.forEach((e) => {
            this.$EVBUS.$emit(e, newData)
          })
          break
        }
      }
    },
  },
}
</script>
